 
// pages/lottery/lottery.js
import api from '../../config/api';
import request from '../../utils/request';
import { shareOptions } from "../../utils/access";
import { jump, getBarAndTitleHeight, goBack } from '../../utils/utils';
var app = getApp()
// 引入动画插件
import lottie from './lottie'
Page({
 
  /**
   * 页面的初始数据
   */
  data: {
    awardIndex:0,
    size: 562,
    ...getBarAndTitleHeight(true),
    currentIndex: 0, // 上一次中奖索引,默认1,同siteNum对比,也是当前的索引
    passIndex: 0, // 已经走过的步长
    trunsNum: 4, // 所转圈数
    lock: true, // 防止重复抽奖,默认能抽
    successShow: false, // 中奖弹窗是否显示
    failShow: false, // 中奖失败弹窗是否显示
    count: 0, // 抽奖次数
    prizeList: [], // 奖品列表
    prizeSeat: 8, // 中奖位置
    prizeName: '', // 奖品名称
    lastUpdateTime: '', // 最后一个商品的修改时间，用于抽奖时校验奖品有无变动
    loadingReward: false,
    successDialogShow: false, // 中奖弹窗是否显示
    showAnimation: false, // 是否显示红圈点点动画
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    that.setData({
      ...getBarAndTitleHeight(),
    });
    // 浮动动画
    this.initAnimation1()
    // 初始化抽奖动画
    this.init()
  },
  onReady: function(e) {
    this.failModal = this.selectComponent('#failModal');
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getDetail();
    this.queryPrizeList();
  },
  /**
   * 初始化抽奖加载动画
   */
  init() {
    if (this.inited) {
      return
    }
    wx.createSelectorQuery()
      .selectAll('#point-canvas')
      .node((res) => {
        if(res[0]){
          const canvas = res[0].node
          const context = canvas.getContext('2d')
          canvas.width = 750
          canvas.height = 1624
          lottie.setup(canvas)
          this.ani = lottie.loadAnimation({
            loop: true,
            autoplay: true,
            animationData: require('./data.js'),
            rendererSettings: {
              context,
            },
          })
          this.inited = true
        }
      })
      .exec()
  },
  /**
   * 初始化抽奖加载动画
   */
  initAnimation1() {
    if (this.inited1) {
      return
    }
    wx.createSelectorQuery()
      .selectAll('#animation1-canvas')
      .node((res) => {
        if(res[0]){
          const canvas = res[0].node
          const context = canvas.getContext('2d')
          canvas.width = 750
          canvas.height = 1624
          lottie.setup(canvas)
          this.ani = lottie.loadAnimation({
            loop: true,
            autoplay: true,
            animationData: require('./data1.js'),
            rendererSettings: {
              context,
            },
          })
          this.inited1 = true
        }
      })
      .exec()
  },
  async getDetail() {
    // 抽奖数据
    const res = await request.get(`${api.getDrawNum}`,{}, { loading: false });
    if (res.httpStatus === 200) {
      this.setData({
        count: res.data,
      });
    }
  },
  //初始化奖品数据 计算角度
  initAdards() {
    var that = this,
    prizeList = that.data.prizeList;
    var t = prizeList.length; // 选项长度
    var e = 1 / t,
      i = 360 / t,
      r = i - 90;
 
    for (var g = 0; g < t; g++) {
      prizeList[g].item2Deg = g * i + 90 - i / 2 + "deg"; //当前下标 * 360/长度 + 90 - 360/长度/2
      prizeList[g].afterDeg = r + "deg";
      prizeList[g].opacity = '1';
    }
    console.log('prizeList-----',prizeList)
    that.setData({
      turnNum: e, // 页面的单位是turn
      prizeList: prizeList,
    })
  },
  // 获取中奖信息
  async getAwardInfo() {
    var that = this;
    // that.setData({
    //   loadingReward: true,
    //   showAnimation: true
    // });
    
    // // 运行抽奖
    // that.getLottery()
    // return
    if (that.data.count === 0) {
      wx.showToast({
        title: '您没有抽奖机会',
        icon: 'none',
      });
      return;
    }
    const { loadingReward } = that.data;
    if (loadingReward) return;
    that.setData({
      loadingReward: true,
      showAnimation: true
    });
    const res = await request.get(api.drawPrize, {
      activityId: 1,
      lastUpdateTime: that.data.lastUpdateTime,
    }, { loading: false });
    if (res.httpStatus === 200) {
      let seat = Number(res.data.prizeSeat);
      this.setData({
        prizeName: res.data.prizeName,
        prizeSeat: seat,
        prizeLevel: res.data.prizeLevel,
      });

      // 运行抽奖
      that.getLottery()

      // 重新获取抽奖次数
      that.getDetail();
    } else {
      if (res.msg === '奖品数据更新') {
        that.queryPrizeList();
      }
      setTimeout(() => {
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000,
        });
      }, 500);
      this.setData({
        loadingReward: false,
        showAnimation: false
      });
      return;
    }
  },
  /**
  * 抽奖处理函数：
  */
  getLottery: function () {
    let that = this;
    let { prizeList, prizeSeat } = that.data;
    // 获取奖品配置
    let runNum = 10,
      len = prizeList.length,
      awardIndex =  prizeSeat

    // 旋转抽奖
    app.runDegs = app.runDegs || 0
    app.runDegs = app.runDegs + (360 - app.runDegs % 360) + (360 * runNum - (awardIndex-0.5) * (360 / len))
    //创建动画
    let animationRun = wx.createAnimation({
      duration: 6000,
      timingFunction: 'ease'
    })
    that.animationRun = animationRun
    animationRun.rotate(app.runDegs).step()
    that.setData({
      awardIndex: awardIndex,
      animationData: animationRun.export()
    })
  },
  animationend(){
    let that = this
    let { prizeSeat } = that.data
    this.setData({
      showAnimation: false
    })
    if (prizeSeat === 8) {
      that.failModal.show();
    } else {
      that.setData({
        successDialogShow: true,
      });
    }
  },
  // 关闭中奖弹窗
  async successModalClose() {
    this.setData({
      successDialogShow: false,
      currentIndex: 0,
      loadingReward: false,
    });

    const res = await request.get(`${api.getPrizeList}`, { activityId: 1 }, { loading: false });
    if (res.httpStatus === 200) {
      this.setData({
        lastUpdateTime: res.data.lastUpdateTime,
      });
    }
  },
  // 关闭中奖失败弹窗
  failModalClose: function () {
    this.failModal.hide();
    this.setData({
      currentIndex: 0,
      loadingReward: false,
    });
  },
  // 跳转中奖纪录页面
  jumpLotteryRecord: function () {
    jump('lotteryRecord');
  },
  // 跳转兑换券页面
  jumpReward: function () {
    jump('coinCertificate');
  },
  // 返回上一页
  jumpBack: function () {
    goBack()
  },
  async queryPrizeList() {
    // 抽奖数据
    const response = await request.get(`${api.getPrizeList}`, { activityId: 1 }, { loading: false });
    const indexArr = [1, 2, 3, 4, 5, 6, 7, 8];
    if (response.httpStatus === 200) {
      let list = response.data.prizeList;
      list.map((item, index) => {
        item.siteNum = indexArr[index];
        item.prizeName = item.prizeName?.substring(0, 6);
        item.key = index + 1;
        if (item.prizeId === 0) {
          item.prizeImgUrl =
            'https://image-classify.daieco.com/kejian-quanzi/4Pppp0lYPed5d144be4d499f658f1e9a09fdc6426571.png';
        }
      });
      this.setData({
        lastUpdateTime: response.data.lastUpdateTime,
        prizeList: list,
      });
      this.initAdards()
    }
  },

  // 用户点击右上角分享
	onShareAppMessage(e) {
    return shareOptions('award', e)
	},
})

